﻿using System.Configuration;
using System.Speech.Synthesis;
using System.Threading;
using System.Windows.Media;

namespace AllInOne
{
    /// <summary>
    /// 播放语音
    /// </summary>
    public static class VoiceHelper
    {
        private static int Volume = 100;
        private static int Rate = 0;
        public static void InitConfig()
        {
            var b = int.TryParse(ConfigurationManager.AppSettings["Volume"], out Volume);
            if (!b)
            {
                Volume = 100;
            }
            else
            {
                if (Volume > 100) Volume = 100;
                if (Volume < 0) Volume = 0;
            }

            var c = int.TryParse(ConfigurationManager.AppSettings["Rate"], out Rate);
            if (!c)
            {
                Rate = -1;
            }
            else
            {
                if (Rate < -10) Rate = -10;
                if (Rate > 10) Rate = 10;
            }
            IsInit = true;
        }

        private static bool IsInit = false;

        public static void Speak(string msg)
        {
            if (!IsInit) InitConfig();
            using (var synthesizer = new SpeechSynthesizer())
            {
                //TODO 此处需要设置音量大小
                synthesizer.Volume = Volume;
                //TODO 此处需要设置语速
                synthesizer.Rate = Rate;
                synthesizer.Speak(msg);
            }
        }

        public static void SpeakAsync(string msg)
        {
            if (!IsInit) InitConfig();
            new Thread(() =>
            {
                using (var synthesizer = new SpeechSynthesizer())
                {
                    //TODO 此处需要设置音量大小
                    synthesizer.Volume = Volume;
                    //TODO 此处需要设置语速
                    synthesizer.Rate = Rate;

                    synthesizer.SpeakAsync(msg);
                    Thread.Sleep(1000);
                }
            }).Start();

        }

        public static void SpeakTest(string msg, int volume, int rate)
        {
            using (var synthesizer = new SpeechSynthesizer())
            {
                //TODO 此处需要设置音量大小
                synthesizer.Volume = volume;
                //TODO 此处需要设置语速
                synthesizer.Rate = rate;
                synthesizer.SpeakAsync(msg);
            }
        }
    }
}